import { createRouter, createWebHistory } from "vue-router";
import home_web from '@/views/Home/index.vue'

const modules: any = import.meta.glob('../views/**/**.vue');

let routes: any = [{
    path: "/",
    name: "home",
    meta: { titel: "Home" },
    component: home_web
}];

if (modules) {
    for (const key in modules) {
        if (isTailIndexVue(key)) {
            //  console.log(checkStr(key));
            let strData = checkStr(key)
            // console.log(strData);

            let strData2 = convertTo1(checkStr(key))
            routes.push({
                path: "/" + strData,
                name: strData2,
                meta: { titel: strData2 },
                component: modules[key],
            })
        }

        // if (Object.prototype.hasOwnProperty.call(modules, key)) {
        //     let name = key.split('.vue')[0].split('/')[key.split('.vue')[0].split('/').length - 1];

        //     // home 从定向
        //     routes.push({
        //         path: `/${name == 'home' ? '' : name}`,
        //         name,
        //         meta: {
        //             title: name,
        //         },
        //         component: modules[key],
        //     });
        // }
    }

    localStorage.setItem('routes', JSON.stringify(routes));
}
//--============================

function isTailIndexVue(str: string) {
    return str.endsWith('index.vue');
}

function checkStr(str: string) {

    //let str = "../views/Component_Communication/01_Props/index.vue";  
    let prefix = "../views/";
    let suffix = "/index.vue";

    // 首先去除前缀  
    let noPrefixStr = str.substring(prefix.length);

    // 然后找到后缀的索引并截取字符串  
    let suffixIndex = noPrefixStr.indexOf(suffix);
    if (suffixIndex !== -1) { // 确保后缀确实存在  
        let result = noPrefixStr.substring(0, suffixIndex);
        return result;
        // console.log(result); // 输出：Component_Communication/01_Props  
    } else {
        //console.log("后缀未找到");
    }
}

function convertTo1(strData: string) {
    // console.log(strData, 'strData');
    if (strData) {
        return strData.replace(/\//g, '_')

    }
}

//--===========================
/*
    希望的格式如下:

    path:'/Component_Communication/01_Props'
    name:'Component_Communication_01_Props'
    component:'Component_Communication/01_Props/index.vue'

    */



// console.log(routes, typeof (routes));


// console.log(routes);
// 导出路由
export default createRouter({
    history: createWebHistory(),
    routes,
});
